<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      :control="control"
      :controlPosition="[]"
      :positionName="''"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    > 
     </TopSearch>
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="[]"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
      
    >
      <template #default="{ row, propname }">
        <div  v-if="propname === 'pays'">
          <el-tag color="#DEEFF1" v-if="row[propname] == '已收款' ">{{row[propname]}}</el-tag>
          <el-tag  v-if="row[propname] == '欠款' " type='warning'>{{row[propname]}}</el-tag>
          <el-tag  v-if="row[propname] == '退款' " type='warning'>{{row[propname]}}</el-tag>
          </div>
      </template>

        <template #search_operate>
            <el-table-column  fixed="right" min-width="200px" label="操作">
              <template #default="scope">
               <div class="flex ">
                <el-link v-if="scope.row.pay == 1"  type="primary" :underline="false" @click="look(scope.$index, scope.row)" class="btn" >查看</el-link >
                <el-link  type="primary" :underline="false"  @click="print(scope.$index, scope.row)" class="btn">打印</el-link >
                <el-link  type="primary" :underline="false"  @click="abandonment(scope.$index, scope.row)" class="btn">作廢</el-link >
                <el-link  v-if="scope.row.pay == 1" type="primary" :underline="false"  @click="collection(scope.row,scope.$index)" class="btn">收款</el-link >
               </div>
              </template>
            </el-table-column>
        </template>
    </ProTable>
    <addEdit :echo="echo" ref="AddEditref" @addConfirm="addConfirm"></addEdit>
  </div>
</template>

<script setup>
import { reactive, ref,onMounted,computed, watch } from "vue"
import { elProps,controlWidth } from "./index.js"
import { setFormConfig } from "./formConfig";
import addEdit from './addEdit/index.vue'
 import {invoice,delInvoice} from '@/http/index.js'
 import {messageBox,message,loading,closeLoading} from '@/common/function.js'
import { useRouter, onBeforeRouteUpdate, useRoute } from "vue-router";
  import {
    subtract,
    multiply,
    divide,
    add
  } from 'high-precision-four-fundamental-rules'

 const echo = ref({})

// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  pays: "收款狀態",
  student_name: "學生名稱",
  school_name: "學校名稱",
  number:'發票編號',
  student_number:'學生編號',
  price:'收款金額',
  debt:'欠款',
  statuss:'狀態',
  remark:'備註',
  notice:'須知',
  create_time:'創建時間',
  update_time:'修改時間',
};
// 表格顶部操作按钮
const control = ["search", "dels", "add"];

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const searchHeader = (e) => {
    Object.assign(obj, e);
      tableList();
};
const AddEditref = ref(null);
const addHeader = async() => {
  echo.value={
    id:'',
    student_id:'',
    student_name:'',
    status:'',
    remark:'',
    notice:'',
    course: [], //課程
    product: [], //產品
    products_group: [], //產品組合
    ticket:[]//
  }
  delete echo.value.id
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = 'add'
};

const look = (index,row)=>{
  console.log(index,row);
  const {id,student_id,username,student_name,status,remark,notice,school_name,create_time,course,product,products_group,ticket} = row
     echo.value = {id,student_id,username,student_name,status,remark,notice,school_name,create_time,course,product,products_group,ticket}
       ticket.map(item=>{
        let selfNumber = Number(item.num)
        let isPercent = false
        let diffVal = 0
        if (item.discount && item.discount !== '' && item.discount !== null) {
          isPercent = item.discount?.indexOf('%') > -1 ? true : false //是否百分比符號
          if (isPercent) {
            diffVal = parseInt(item.discount)* 0.01
          }else{
            diffVal = 0 
            }
        } else {
          diffVal = 0
        }
                item.ticket_item = item.ticket_item?.map(v => {
          let price = multiply(selfNumber, (Number(v['price']) / Number(v.num)), 2)
          let discount = isPercent ? add(item.discount_price, multiply(price, diffVal, 2), 2) : add(item
            .discount_price,
            diffVal, 2)
          let num = item.total_prices - subtract(price, discount, 2)
          if (num === 0 && selfNumber !== 0) {
            v.isFlag = true
          item.deadline = v.deadline
          } else {
            v.isFlag = false
          }
          return v
        })
      })
 AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = 'edit'
}
const router = useRouter();
const route = useRoute();
const print = (index,row)=>{
console.log(route);
    let {href} = router.resolve({
          path: '/invoicePrint',
          query: {
           data:JSON.stringify(row),
           username:localStorage.getItem('username')
          }
        })
        window.open(href, '', 'height=700,width=800,top=300,left=800')
}
import { userouteStore } from "@/stores/index.js";
import { storeToRefs } from "pinia";
const store = userouteStore();
const collection =(row)=>{
  console.log(row);
          router.push({
          name: 'gathering',
          query:{showInfo:true}
        })
        store.showInfo = true
        store.data = JSON.stringify(row)
}
const abandonment = (index,row)=>{
  messageBox().then(async()=>{
  delTableList(row.id)
  })
}

const delTableList = async(id)=>{
        const data = await delInvoice(id) 
          if (data.code  == 200) {
              tableList()
              message('已成功刪除該發票')
          }else{
              message('刪除發票失敗')
          }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
    let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
const delsHeader = () => {
      messageBox().then(async () => {
          delTableList(ids.value)
    }).catch(e=>{})
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = async({ e, type }) => {
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
  await tableList()
};


const obj = reactive({
  school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
  type:2
});
const props = defineProps({
  echo:Object
})
obj.student_id = props.echo.id
console.log(props.echo.id);
watch(()=>props.echo,(newval)=>{
obj.student_id = newval.id
})
const tableData = ref([])
const tableList = async ()=>{
  loading()
  const data = await invoice(obj)
  console.log(data);
  if (data.code == 200) {
    data.data.data.forEach(e =>{
       e.status == 1 ? e.statuss= '正常' :e.statuss = '禁用'
       e.pay == 1 ? e.pays= '欠款' : e.pay == 2 ? e.pays= '已收款' : e.pays= '退款'
    });
        page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    tableData.value = data.data.data
  }
  closeLoading()
}

const addConfirm = async()=>{
  await tableList()
}

const pageRefresh = async()=>{
  await tableList()
}

defineExpose({
  tableList,obj
})
</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 5px;
}
.button{
  color: #fff;
}
.btn{
  margin-right: 10px;
}
</style>